<template>
  <div>
    <div ref="mapContainer" class="map-container"></div>
    <div class="controls" v-if="!disable">
      <button @click="drawFence">绘制电子围栏</button>
      <button @click="saveFence">保存围栏</button>
      <!-- <button @click="startMonitoring">开始监控</button>
      <button @click="stopMonitoring">停止监控</button> -->
    </div>
    <!-- <div v-if="status" class="status">{{ status }}</div> -->
  </div>
</template>

<script lang="ts">
import { defineComponent, ref, onMounted, onUnmounted } from 'vue';
import AMapLoader from '@amap/amap-jsapi-loader';

export default defineComponent({
  name: 'AmapFence',
  emits: ['save'],
  props: {
    points: {
      type: Array,
      required: true
    },
    eFences: {
      type: Array, //多个电子围栏
      required: true
    },
    disable:{
      type:Boolean,
      required:true
    }
  },

  setup(props, { emit }) {
    const mapContainer = ref<HTMLElement | null>(null);
    const map = ref<AMap.Map | null>(null);
    const AMap = ref<any>(null);
    const polygon = ref<AMap.Polygon | null>(null);
    const polygonEditor = ref<AMap.PolygonEditor | null>(null);
    const mouseTool = ref<AMap.MouseTool | null>(null);
    const status = ref<string>('');
    const timer = ref<NodeJS.Timeout | null>(null);
    const fencePoints = ref<double[][]>([]);

    // 初始化地图
    const initMap = async () => {
      try {
        AMap.value = await AMapLoader.load({
          key: '479bb68a292209b4f9649f91b1427c46', // 替换为你的key
          version: '2.0',
          plugins: ['AMap.PolygonEditor', 'AMap.MouseTool']
        });

        if (mapContainer.value) {
          map.value = new AMap.value.Map(mapContainer.value, {
            viewMode: '2D',
            zoom: 15,
            center: [120.53535, 31.16828]
          });
        }
      } catch (error) {
        console.error('地图加载失败:', error);
        status.value = '地图加载失败，请检查Key配置';
      }
    };

    const showFence = (v: Array) => {
      if (!map.value || !AMap.value) return; // 清除旧的围栏

      if (polygon.value) {
        map.value.remove(polygon.value);
        polygon.value = null;
      } // 创建新的多边形围栏

      polygon.value = new AMap.value.Polygon({
        path: JSON.parse(v),
        strokeColor: '#FF33FF',
        strokeWeight: 3,
        fillColor: '#1791fc',
        fillOpacity: 0.4
      });
      map.value.add(polygon.value);
      map.value.setFitView(); // 自适应视野
    };

    //显示多个电子围栏
    const showFenceList = (v: Array) => {
      if (!map.value || !AMap.value) return; // 清除旧的围栏

      map.value.clearMap();

      v.forEach((singleEFence) => {
        let SinglePolygon = new AMap.value.Polygon({
          path: JSON.parse(singleEFence),
          strokeColor: '#FF33FF',
          strokeWeight: 3,
          fillColor: '#1791fc',
          fillOpacity: 0.4
        });
        map.value.add(SinglePolygon);
        map.value.setFitView();
      });


    };

    // 绘制电子围栏
    const drawFence = () => {
      if (!map.value || !AMap.value) return;

      // 清除已有围栏
      if (polygon.value) {
        map.value.remove(polygon.value);
        polygon.value = null;
      }

      // 使用鼠标工具绘制多边形
      mouseTool.value = new AMap.value.MouseTool(map.value);
      mouseTool.value.polygon({
        strokeColor: '#FF33FF',
        strokeOpacity: 1,
        strokeWeight: 2,
        fillColor: '#1791fc',
        fillOpacity: 0.4
      });

      mouseTool.value.on('draw', (e: any) => {
        const obj = e.obj;
        polygon.value = obj;
        mouseTool.value?.close();

        // 初始化多边形编辑器
        polygonEditor.value = new AMap.value.PolygonEditor(map.value, obj);
        polygonEditor.value.open();
      });
    };

    // 保存电子围栏
    const saveFence = () => {
      if (!polygon.value) {
        status.value = '请先绘制电子围栏';
        return;
      }

      const path = polygon.value.getPath();

      fencePoints.value = path.map((point: AMap.LngLat) => [point.getLng(), point.getLat()]);

      console.log('电子围栏坐标:', fencePoints.value);
      emit('save', fencePoints.value);
      status.value = `围栏已保存，共${fencePoints.value.length}个顶点`;
    };

    // 检查点是否在围栏内
    const checkInFence = (lnglat: AMap.LngLat): boolean => {
      if (!polygon.value || !AMap.value) return false;

      return AMap.value.GeometryUtil.isPointInRing(lnglat, polygon.value.getPath());
    };

    // 模拟监控点
    const monitorPoint = () => {
      if (!map.value || !polygon.value || !AMap.value) return;

      // 随机生成一个测试点
      const center = map.value.getCenter();
      const randomLng = center.getLng() + (Math.random() - 0.5) * 0.02;
      const randomLat = center.getLat() + (Math.random() - 0.5) * 0.02;
      const point = new AMap.value.LngLat(randomLng, randomLat);

      // 创建标记点
      const marker = new AMap.value.Marker({
        position: point,
        map: map.value
      });

      // 检查是否在围栏内
      const isInside = checkInFence(point);

      // 根据结果设置不同颜色
      marker.setContent(
        `<div style="background: ${isInside ? 'green' : 'red'};
                    width: 10px;
                    height: 10px;
                    border-radius: 50%;"></div>`
      );

      // 触发业务逻辑
      if (isInside) {
        status.value = `点(${randomLng.toFixed(6)}, ${randomLat.toFixed(6)})进入电子围栏区域`;
        // 这里可以触发业务逻辑，如发送通知等
      }
    };

    // 定时监控
    const startMonitoring = () => {
      if (!polygon.value) {
        status.value = '请先绘制电子围栏';
        return;
      }

      stopMonitoring();
      timer.value = setInterval(monitorPoint, 2000);
      status.value = '监控已启动，每2秒检测一次';
    };

    const stopMonitoring = () => {
      if (timer.value) {
        clearInterval(timer.value);
        timer.value = null;
        status.value = '监控已停止';
      }
    };

    watch(
      () => props.points,
      (v: Array) => {
        // console.log('watch points-------' + v);
        showFence(v);
      },
      { immediate: true }
    );

    watch(
      () => props.eFences,
      (v: Array) => {
        showFenceList(v);
      },
      { immediate: true }
    );

    onMounted(() => {
      initMap();
    });

    onUnmounted(() => {
      stopMonitoring();
      if (map.value) {
        map.value.destroy();
      }
    });

    return {
      mapContainer,
      drawFence,
      saveFence,
      startMonitoring,
      stopMonitoring,
      status
    };
  }
});
</script>

<style scoped>
.map-container {
  width: 100%;
  height: 600px;
}

.controls {
  margin: 10px 0;
  display: flex;
  gap: 10px;
}

button {
  padding: 8px 12px;
  background: #1791fc;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
}

button:hover {
  background: #1177d4;
}

.status {
  margin-top: 10px;
  padding: 8px;
  background: #f0f0f0;
  border-radius: 4px;
}
</style>
